//
//  TSWithDrawUSDTHeaderView.swift
//  TSProfitProject
//
//  Created by TMS on 2019/11/5.
//  Copyright © 2019 TMS. All rights reserved.
//

import UIKit

protocol TSWithDrawUSDTHeaderViewDelegate : NSObjectProtocol {
    func fitToWithdraw(usdt:String, bankpwd:String, usdt_address:String?)
}

extension TSWithDrawUSDTHeaderView : UITextFieldDelegate {
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        
        let newString = (textField.text! as NSString).replacingCharacters(in: range, with: string)
        let expression = "^[0-9]*((\\.|,)[0-9]{0,2})?$"
        let regex = try! NSRegularExpression(pattern: expression, options: NSRegularExpression.Options.allowCommentsAndWhitespace)
        let numberOfMatches = regex.numberOfMatches(in: newString, options:NSRegularExpression.MatchingOptions.reportProgress, range: NSMakeRange(0, (newString as NSString).length))
        return numberOfMatches != 0
    }
    
    func textFieldDidChangeSelection(_ textField: UITextField) {
        
        let usdt = NSString.init(string: cashField.text ?? "0")
        USDTField.text = String.init(format: "%.2f", usdt.doubleValue / rate)
    }
}

class TSWithDrawUSDTHeaderView: UIView {
    
    weak var delegate : TSWithDrawUSDTHeaderViewDelegate? = nil
    var rateLabel : UILabel!
    var handleLabel : UILabel!
    var cashField : UITextField!
    var USDTField : UITextField!
    var passwordField : UITextField!
    var walletField : UITextField!
    var rate : Double = 0

    override init(frame: CGRect) {
        super.init(frame: frame)
        configViews()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setupRate(rate:Double) {
        self.rate = rate
        self.rateLabel.text = String.init(format: "USDT实时汇率：%.2f", self.rate)
    }
    
    func checkCommitCondition() -> Bool {
        
        let usdt = USDTField.text?.removeAllSapce as NSString?
        guard usdt?.doubleValue != 0 else {
            CBToast.showToastAction(message: "USDT必须大于0")
            return false
        }
        
        guard passwordField.text?.removeAllSapce.count != 0 else {
            CBToast.showToastAction(message: "请输入取款密码")
            return false
        }
        return true
    }
    
    @objc func commitAction() {
        
        if checkCommitCondition() {
            
            if self.delegate != nil {
                self.delegate?.fitToWithdraw(usdt: USDTField.text!, bankpwd: passwordField.text!.removeAllSapce, usdt_address: walletField.text ?? "")
            }
        }
    }
    
    func refreshHeaderView(withdrawType:Int) {
        switch withdrawType {
        case 0:
            handleLabel.text = String.init(format: "可提现金额：%.2f", TSLoginManager.shared._usermodel!.yingli)
        case 1:
            handleLabel.text = String.init(format: "可提现金额：%.2f", TSLoginManager.shared._usermodel!.zhongxin)
        default: break
        }
    }
    
    func configViews() {
        
        rateLabel = createLabel(text: "USDT实时汇率：7.10")
        self.addSubview(rateLabel)
        rateLabel.snp.makeConstraints { (make) in
            make.top.equalToSuperview()
            make.left.equalTo(15)
            make.width.lessThanOrEqualTo(SCREEN_WIDTH - 2*15)
        }
        
        let line1 = drawLine()
        self.addSubview(line1)
        line1.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview().inset(15)
            make.top.equalTo(rateLabel.snp.bottom).offset(17)
            make.height.equalTo(1)
        }
        
        handleLabel = createLabel(text: "可提现金额：0.00")
        self.addSubview(handleLabel)
        handleLabel.snp.makeConstraints { (make) in
            make.top.equalTo(rateLabel.snp.bottom).offset(35)
            make.left.equalTo(rateLabel)
            make.width.lessThanOrEqualTo(SCREEN_WIDTH - 2*15)
        }
        
        let sectionView = UIView.init()
        sectionView.backgroundColor = UIColor.hexadecimalColor(hexadecimal: "#F7F7F7")
        addSubview(sectionView)
        sectionView.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.top.equalTo(handleLabel.snp.bottom).offset(17)
            make.height.equalTo(10)
        }
        
//        let line1 = drawLine()
//        self.addSubview(line1)
//        line1.snp.makeConstraints { (make) in
//            make.left.equalTo(12)
//            make.top.equalTo(handleLabel.snp.bottom).offset(30)
//            make.size.equalTo(CGSize(width: SCREEN_WIDTH-2*12, height: 1))
//        }
        
        let unitLabel = createLabel(text: "USDT")
        self.addSubview(unitLabel)
        unitLabel.snp.makeConstraints { (make) in
            make.left.equalTo(handleLabel)
            make.top.equalTo(sectionView.snp.bottom).offset(17)
            make.width.lessThanOrEqualTo(handleLabel)
        }
        
        let line2 = drawLine()
        self.addSubview(line2)
        line2.snp.makeConstraints { (make) in
            make.left.equalTo(line1)
            make.top.equalTo(unitLabel.snp.bottom).offset(17)
            make.size.equalTo(line1)
        }
        
        let cashContainer = UIView.init()
        cashContainer.backgroundColor = WHITE_COLOR
        self.addSubview(cashContainer)
        cashContainer.snp.makeConstraints { (make) in
            make.left.equalTo(handleLabel)
            make.top.equalTo(line2.snp.bottom)
            make.size.equalTo(CGSize(width: SCREEN_WIDTH - 2*15, height: 50))
        }
        
        let utilCashLabel = createLabel(text: "RMB")
        cashContainer.addSubview(utilCashLabel)
        utilCashLabel.snp.makeConstraints { (make) in
            make.centerY.right.equalToSuperview()
        }
        
        cashField = createInputField(placeholder: "请输入取款金额")
        cashField.keyboardType = .decimalPad
        cashField.delegate = self
        cashContainer.addSubview(cashField)
        cashField.snp.makeConstraints { (make) in
            make.left.top.bottom.equalToSuperview()
            make.right.equalTo(utilCashLabel.snp.left).offset(-10)
        }
        
        let line3 = drawLine()
        self.addSubview(line3)
        line3.snp.makeConstraints { (make) in
            make.left.equalTo(line1)
            make.top.equalTo(cashContainer.snp.bottom)
            make.size.equalTo(line1)
        }
        
        let USDTContainer = UIView.init()
        USDTContainer.backgroundColor = WHITE_COLOR
        self.addSubview(USDTContainer)
        USDTContainer.snp.makeConstraints { (make) in
            make.left.equalTo(handleLabel)
            make.top.equalTo(line3.snp.bottom)
            make.size.equalTo(cashContainer)
        }
        
        let utilUSDTLabel = createLabel(text: "USDT")
        USDTContainer.addSubview(utilUSDTLabel)
        utilUSDTLabel.snp.makeConstraints { (make) in
            make.centerY.right.equalToSuperview()
            make.width.equalTo(40)
        }
        
        USDTField = createInputField(placeholder: "请输入取款金额")
        USDTField.text = "0.00"
        USDTField.isEnabled = false
        USDTContainer.addSubview(USDTField)
        USDTField.snp.makeConstraints { (make) in
            make.left.top.bottom.equalToSuperview()
            make.right.equalTo(utilUSDTLabel.snp.left).offset(-10)
        }
        
        let line4 = drawLine()
        self.addSubview(line4)
        line4.snp.makeConstraints { (make) in
            make.left.equalTo(line1)
            make.top.equalTo(USDTContainer.snp.bottom)
            make.size.equalTo(line1)
        }
        
        passwordField = createInputField(placeholder: "请输入取款密码")
        passwordField.keyboardType = .phonePad
        self.addSubview(passwordField)
        passwordField.snp.makeConstraints { (make) in
            make.left.equalTo(rateLabel)
            make.right.equalTo(-15)
            make.top.equalTo(line4.snp.bottom)
            make.height.equalTo(50)
//            make.size.equalTo(CGSize(width: SCREEN_WIDTH - 2*34, height: 50))
        }
        
        let line5 = drawLine()
        self.addSubview(line5)
        line5.snp.makeConstraints { (make) in
            make.left.equalTo(line1)
            make.top.equalTo(passwordField.snp.bottom)
            make.size.equalTo(line1)
        }
        
        walletField = createInputField(placeholder: "请输入钱包地址（银行提款不填）")
        self.addSubview(walletField)
        walletField.snp.makeConstraints { (make) in
            make.left.right.height.equalTo(passwordField)
            make.top.equalTo(line5.snp.bottom)
        }
        
        let line6 = drawLine()
        self.addSubview(line6)
        line6.snp.makeConstraints { (make) in
            make.left.equalTo(line1)
            make.top.equalTo(walletField.snp.bottom)
            make.size.equalTo(line1)
            
        }
        
        let footerView = UIView.init()
        footerView.backgroundColor = WHITE_COLOR
        self.addSubview(footerView)
        footerView.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.top.equalTo(line6.snp.bottom)
            make.height.equalTo(88)
        }
        
        let commitBtn = UIButton.init(type: .system)
        commitBtn.setTitle("提交", for: .normal)
        commitBtn.setTitleColor(WHITE_COLOR, for: .normal)
        commitBtn.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: .medium)
        commitBtn.backgroundColor = BASE_RED_COLOR
        commitBtn.layer.cornerRadius = 24
        commitBtn.layer.masksToBounds = true
        commitBtn.addTarget(self, action: #selector(commitAction), for: .touchUpInside)
        footerView.addSubview(commitBtn)
        commitBtn.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalTo(30)
            make.size.equalTo(CGSize(width: SCREEN_WIDTH*0.682, height: 48))
        }
    }
    
    func createInputField(placeholder:String) -> UITextField {
        
        let string = placeholder
        let attributeStr = NSMutableAttributedString.init(string: string)
        attributeStr.addAttributes([NSAttributedString.Key.foregroundColor:UIColor.hexadecimalColor(hexadecimal: "#989898"), NSAttributedString.Key.font:UIFont.systemFont(ofSize: 14, weight: .medium)], range: NSMakeRange(0, string.count))
        
        let textField = UITextField.init()
        textField.font = UIFont.systemFont(ofSize: 14, weight: .medium)
        textField.textColor = UIColor.hexadecimalColor(hexadecimal: "#282828")
        textField.attributedPlaceholder = (attributeStr.copy() as! NSAttributedString)
        textField.borderStyle = .none
        textField.clearButtonMode = .whileEditing
        return textField
    }

    func createLabel(text:String) -> UILabel {
        
        let label = UILabel.init()
        label.text = text
        label.textColor = UIColor.hexadecimalColor(hexadecimal: "#282828")
        label.font = UIFont.systemFont(ofSize: 14, weight: .medium)
        return label
    }
    
    func drawLine() -> UIView {
        let line = UIView.init()
        line.backgroundColor = UIColor.hexadecimalColor(hexadecimal: "#F5F5F5")
        return line
    }

}
